package com.vogue.supplymall.shop.controller;

import com.vogue.supplymall.account.domain.model.BaseCategory;
import com.vogue.supplymall.account.domain.service.BaseCategoryService;
import com.vogue.supplymall.common.domain.dto.SearchInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.tool.VestUtils;
import com.vogue.supplymall.common.exception.DataNotFindException;
import com.vogue.supplymall.entmanagement.domain.dto.LicenceApplyEditDTO;
import com.vogue.supplymall.entmanagement.domain.service.LicenceApplyService;
import com.vogue.supplymall.match.domain.model.MatchOrgan;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.shop.common.CheckSearchInfoUtils;
import com.vogue.supplymall.shop.domain.model.Shop;
import com.vogue.supplymall.shop.domain.service.RelShopCategoryService;
import com.vogue.supplymall.shop.domain.service.ShopService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提供店铺信息的controller
 * @aouthor zhangliang
 * @create 2017 -12-01
 */
@RestController
public class ShopController extends BaseController {
    /**
     * The constant LOGGER_SHOPCONTROLLER.
     */
    public static final Logger LOGGER_SHOPCONTROLLER = LoggerFactory.getLogger(ShopController.class);

    @Resource
    private ShopService shopService;
    @Resource
    private MatchOrganService matchOrganService;
    @Resource
    private LicenceApplyService licenceApplyService;
    @Resource
    private MessageSource messageSource;
    @Resource
    private BaseCategoryService baseCategoryService;
    @Resource
    private RelShopCategoryService relShopCategoryService;

	/**
	 * Gets shop by id.
	 * 根据id检索店铺
	 *
	 * @param appver the appver
	 * @param id     the id
	 * @return the shop by id
	 */
	@RequestMapping(value = "/ns/{appver}/shop/get/{id}", method = RequestMethod.POST)
    public ResponseEntity<Object> getShopById(@PathVariable("appver") String appver, @PathVariable("id") Long id) {
        Long loginId = null;
        if (SecurityUtils.getSubject().isAuthenticated()) {
            UserInfo info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            loginId = info.getLoginId();
            LOGGER_SHOPCONTROLLER.info("login id：" + info.getLoginId());
        } else {
            LOGGER_SHOPCONTROLLER.info("no login");
        }

        return new ResponseEntity<>(shopService.findById(id, loginId), HttpStatus.OK);
    }

	/**
	 * Gets shop.
	 * 根据条件检索店铺信息
	 *
	 * @param appver     the appver
	 * @param searchInfo the search info
	 * @return the shop
	 */
	@RequestMapping(value = "/ns/{appver}/shop/list", method = RequestMethod.POST)
    public ResponseEntity<Object> searchShop(@PathVariable("appver") String appver, @RequestBody SearchInfo searchInfo) {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            UserInfo info = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            searchInfo.setLoginId(info.getLoginId());
            LOGGER_SHOPCONTROLLER.info("login id：" + info.getLoginId());
        } else {
            LOGGER_SHOPCONTROLLER.info("no login");
        }

        if (CheckSearchInfoUtils.apply(searchInfo)) {
            LOGGER_SHOPCONTROLLER.info("searchInfo check failed!");
            return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK);
        }
        try {
        	Object result = null;
        	if (VestUtils.isVisitFromPC()) {
        		result = shopService.findListBySearchInfo(searchInfo);
        	} else {
        		result = shopService.findBySearchInfo(searchInfo);
        		LOGGER_SHOPCONTROLLER.info("result.size:" + ((List<Map<String, Object>>) result).size());
        	}
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (RuntimeException ex) {
            throw new DataNotFindException("");
        }
    }

	/**
	 * 获取某个店铺的详细信息
	 *
	 * @param appver 版本号
	 * @param id     店铺id
	 * @return shop detail
	 */
	@RequestMapping(value = "/ns/{appver}/shop/detail/{id}", method = RequestMethod.POST)
    public ResponseEntity<Object> getShopDetail(@PathVariable("appver") String appver, @PathVariable("id") Long id) {
    	Map<String, Object> result = new HashMap<>();
    	Shop shop = shopService.get(id);
    	if (shop == null) {
    		 throw new DataNotFindException("");
    	} else {
    		//获取企业简介
    		MatchOrgan organ = matchOrganService.selectOneByWhr("type=1 and syscodeid=" + shop.getSyscodeid());
    		if (organ != null) {
    			result.put("entinfo", organ.getOrganinfo());
    		}
    		//获取证照相关信息
    		LicenceApplyEditDTO dto = licenceApplyService.findShopApply(id);
    		if (dto != null && dto.getCurrentDTO() != null) {
    			result.put("applyinfo", dto.getCurrentDTO());
    		} else {
    			result.put("applyinfo", null);
    		}
    	}
    	return new ResponseEntity<>(result, HttpStatus.OK);
    }

	/**
	 * 获取店铺的对应类别
	 *
	 * @param appver appver
	 * @param id     id
	 * @return shop category
	 */
	@RequestMapping(value = "/ns/{appver}/shop/category/{id}", method = RequestMethod.POST)
    public ResponseEntity<Object> getShopCategory(@PathVariable("appver") String appver, @PathVariable("id") Long id) {
    	List<Map<String, String>> resultList = new ArrayList<>();
    	List<BaseCategory> list = baseCategoryService.findAll();
    	List<Map<String, Object>> categoryList = shopService.findShopCategoryIds(id);
    	for (Map<String, Object> map : categoryList) {
    		for (BaseCategory bc : list) {
    			if (((BigInteger) map.get("id")).longValue() == bc.getId().longValue()) {
    				Map<String, String> tmpmap = new HashMap<>();
    				tmpmap.put("id", String.valueOf(map.get("id")));
    				tmpmap.put("name", bc.getName());
    				resultList.add(tmpmap);
    				continue;
        		}
    		}
    	}
    	return new ResponseEntity<>(resultList, HttpStatus.OK);
    }

	/**
	 * 获取店铺集团所有的有效分类
	 *
	 * @param appver    the appver
	 * @param syscodeid the syscodeid
	 * @return ent category
	 */
	@RequestMapping(value = "/ns/{appver}/shop/entcategory/{syscodeid}", method = RequestMethod.POST)
    public ResponseEntity<Object> getEntCategory(@PathVariable("appver") String appver, @PathVariable("syscodeid") Long syscodeid) {
    	List<Map<String, String>> resultList = new ArrayList<>();
    	List<BaseCategory> list = baseCategoryService.findAll();
    	List<Map<String, Object>> categoryList = relShopCategoryService.findAllCategoryIds(syscodeid);
    	for (Map<String, Object> map : categoryList) {
    		for (BaseCategory bc : list) {
    			if (((BigInteger) map.get("id")).longValue() == bc.getId().longValue()) {
    				Map<String, String> tmpmap = new HashMap<>();
    				tmpmap.put("id", String.valueOf(map.get("id")));
    				tmpmap.put("name", bc.getName());
    				resultList.add(tmpmap);
    				continue;
        		}
    		}
    	}
    	return new ResponseEntity<>(resultList, HttpStatus.OK);
    }
}
